import json
import logging
from redis import ConnectionPool, Redis
from aliyunsdkcore.client import AcsClient
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest

class Aliyun():
    def __init__(self):
        # 阿里云登陆信息
        self.AccessKey_ID = ''
        self.AccessKey_Secret = ''
        self.Region_Id = 'cn-hangzhou'
        # 阿里云ecs列表接口参数
        self.request = DescribeInstancesRequest()
        self.request.set_accept_format('json')   # 返回的数据格式
        # self.request.set_VpcId("")   # 机器所在vpc id
        # self.request.set_SecurityGroupId("") # 机器所属安全组id
        self.request.set_VSwitchId("") # 机器所属交换机
        self.request.set_PageSize(100)  # 最大机器个数
        self.request.set_Status("Running")  #  机器状态
    # 处理数据，得到{ip: hostname}字典数据
    def get_instance_list(self):
        response = self._send_request(self.request)
        instance_li = []
        instance_name = []
        if response is not None:
            instance_list = response.get('Instances').get('Instance')
            for instance in instance_list:
                instance_dict = {}
                instance_dict['name'] = instance['InstanceName']
                instance_dict['value'] = instance['VpcAttributes']['PrivateIpAddress']['IpAddress'][0]
                instance_li.append(instance_dict)
                instance_name.append(instance['InstanceName'])
            return instance_li, instance_name
    # 获取阿里云机器列表原始json数据
    def _send_request(self, request):
        client = AcsClient(self.AccessKey_ID, self.AccessKey_Secret, self.Region_Id)
        try:
            response_str = client.do_action_with_exception(request)
            response_detail = json.loads(response_str)
            return response_detail
        except Exception as e:
            logging.error(e)


if __name__ == "__main__":
    instance_list, instance_name = Aliyun().get_instance_list()
    pool = ConnectionPool(host="127.0.0.1", port=6379, decode_responses=True)
    rdb = Redis(connection_pool=pool)
    # 更新key值
    try:
        for instance in instance_list:
            status = rdb.get(instance['name'])
            if status is None:
                rdb.set(instance['name'], instance['value'])
            else:
                if status != instance['value']:
                    rdb.set(instance['name'], instance['value'])
    except Exception as e:
        logging.error(e)
    # 删除key值
    try:
        for rdb_instance in rdb.keys():
            if rdb_instance not in instance_name:
                print(rdb_instance)
                rdb.delete(rdb_instance)
    except Exception as e:
        logging.error(e)
